<template>
	<div class="page-container">
		<h1>页面性能测试</h1>
		<el-form :model="form" label-position="top">
			<el-form-item label="迭代次数">
				<el-input v-model.trim.number="form.iterations" placeholder="请输入要测试的迭代次数"></el-input>
			</el-form-item>
			<el-form-item>
				<el-button type="primary" @click="testPerformance">测试</el-button>
			</el-form-item>
		</el-form>
		<div v-if="results">
			<p>计算 {{ form.iterationsOut }} 次圆周率的响应时间为 {{ results }} ms</p>
		</div>
		
	</div>
</template>

<script>
	export default {
		data() {
			return {
				form: {
					iterations: 10000000,
					iterationsOut: null
				},
				results: null,
			};
		},
		methods: {
			testPerformance() {
				const iterations = this.form.iterations;
				if (!iterations) {
					this.$message.error('请输入迭代次数！');
					return;
				}
				const startTime = Date.now();
				this.calculatePi(iterations);
				const endTime = Date.now();
				this.results = endTime - startTime;
				this.form.iterationsOut = iterations;
			},
			calculatePi(iterations) {
				let pi = 0;
				let sign = 1;
				for (let i = 0; i < iterations; i++) {
					pi += sign / (2 * i + 1);
					sign = -sign;
				}
				pi *= 4;
				return pi;
			},
		},
	};
</script>
